package cn.darkhorse.admin;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.SqlServerTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import org.jetbrains.annotations.NotNull;

import java.util.Collections;
import java.util.function.Consumer;

import static com.baomidou.mybatisplus.generator.config.rules.DbColumnType.BIG_DECIMAL;

/**
 * MyBatisPlus代码生成器（新），基本满足使用了。
 * 官方文档-代码生成器配置新：https://baomidou.com/pages/981406/
 *
 */
public class MyBatisPlusCodeGeneratorUtils4MySql2 {

//    public static final String MODULE_NAME = "mesjob";
    public static final String MODULE_NAME = "messystem";
    public static final String JDBC = "jdbc:mysql://192.168.68.129:3306/%s?";
//    public static final String JDBC = "jdbc:sqlserver://localhost:1433;DatabaseName=";
    private  static String dbName = "iot-system-standard";
    private  static String dbUsername = "root";
    private  static String dbPassword = "root";
//    private  static String dbPassword = "root";
    private  static String outputDir = "D:\\workspace\\example";
    private  static String author = "yuanjun";
    private  static String tableName = "";

    /**
     *
     */
//    private static String[] tables = {"mes_job_fire_working","mes_job_fire_after","mes_job_fire_apply","mes_job_fire_audit","mes_job_fire_before"};
    private static String[] tables = {"configuration_project"};

    public static void main(String[] args) {

        for (String name :
                tables) {
            tableName = name;
            runCodeGenerator();
        }


    }

    /**
     * 快速生成
     */
    private static void runCodeGenerator() {
        FastAutoGenerator.create(getDataSourceConfig())
                .globalConfig(getGlobalConfig())
                .packageConfig(getPackageConfig())
                .strategyConfig(getStrategyConfig())
                /**
                 * 默认的是Velocity引擎模板。也可使用其他的。注意引入模板引擎依赖
                 */
                //.templateEngine(new BeetlTemplateEngine())
                //.templateEngine(new FreemarkerTemplateEngine())
                .execute();

    }



    /**
     * 数据库配置(DataSourceConfig)
     * @return
     */
    private static DataSourceConfig.Builder getDataSourceConfig() {
        /**
         * TODO 数据库配置
         */
//        String url = JDBC + dbName;
        String url = String.format(JDBC,dbName) + "useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
        String username = dbUsername;
        String password = dbPassword;
        DataSourceConfig.Builder builder = new DataSourceConfig.Builder(url, username, password);
        builder.typeConvert(new SqlServerTypeConvert(){
            /**
             * @param globalConfig
             * @param tableField
             * @return
             */
            @Override
            public IColumnType processTypeConvert(@NotNull GlobalConfig globalConfig, @NotNull TableField tableField) {
                if(tableField.getType().contains("decimal")){
                    return BIG_DECIMAL;
                }
                return super.processTypeConvert(globalConfig, tableField);
            }
        });
        return builder;
    }

    /**
     * 全局配置(GlobalConfig)
     * @return
     */
    private static Consumer<GlobalConfig.Builder> getGlobalConfig() {
        Consumer<GlobalConfig.Builder> consumer = new Consumer<GlobalConfig.Builder>() {
            @Override
            public void accept(GlobalConfig.Builder builder) {
                builder.fileOverride() // 覆盖已生成文件
                        // 开启 swagger 模式
                        .enableSwagger()
                        // TODO 设置作者
                        .author(author)
                        // TODO 指定输出目录
                        .outputDir(outputDir)
                        .build();
            }
        };
        return consumer;
    }

    /**
     * 包配置(PackageConfig)
     */
    private static Consumer<PackageConfig.Builder> getPackageConfig() {
        Consumer<PackageConfig.Builder> consumer = new Consumer<PackageConfig.Builder>() {
            @Override
            public void accept(PackageConfig.Builder builder) {
                builder
                        // TODO 设置父包模块名
                        .moduleName(MODULE_NAME)
                        // TODO 设置父包名
                        .parent("cn.darkhorse")
                        // TODO 设置mapperXml生成路径
                        .pathInfo(Collections.singletonMap(OutputFile.mapperXml, outputDir + "\\mapper"))
                        // 设置 Entity 包名
                        .entity("pojo")
                        // 设置 Service 包名
                        .service("service")
                        // 设置 Service Impl 包名
                        .serviceImpl("service.impl")
                        // 设置 Controller 包名
                        .controller("controller")
                        .build();
            }
        };
        return consumer;
    }

    /**
     * 策略配置(StrategyConfig)
     * @return
     */
    private static Consumer<StrategyConfig.Builder> getStrategyConfig(){
        Consumer<StrategyConfig.Builder> consumer = new Consumer<StrategyConfig.Builder>() {
            @Override
            public void accept(StrategyConfig.Builder builder) {

                /**
                 * 策略配置
                 */
                builder
//                        .addTablePrefix("mes_") // TODO 设置过滤表前缀
                        // TODO 设置需要生成的表 不添加生成所有表
                        .addInclude(tableName)
                       .build();

                /**
                 * Entity 策略配置
                 */
                builder.entityBuilder()
                        // 开启 lombok 模型
                        .enableLombok()
                        // 全局主键类型
                        .idType(IdType.AUTO)
                        // TODO 格式化文件名称
//                        .formatFileName("%sDO")
                        .build();

                /**
                 * Mapper 策略配置
                 */
                builder.mapperBuilder()
                        // 启用 BaseResultMap 生成
                        .enableBaseResultMap()
                        // 启用 BaseColumnList
                        .enableBaseColumnList()
                        .build();

                /**
                 * Service 策略配置
                 */
                builder.serviceBuilder()
                        .formatServiceFileName("%sService")
                        .formatServiceImplFileName("%sServiceImpl")
                        .build();

                /**
                 * Controller 策略配置
                 */
                builder.controllerBuilder()
                        // 开启生成@RestController 控制器
                        .enableRestStyle()
                        // 转换文件名称
                        .formatFileName("%sController")
                        .build();
            }
        };
        return consumer;
    }

}
